package com.mproject.activity.project;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.mproject.activity.C2DMMessageReceiver;
import com.mproject.activity.R;
import com.mproject.adapter.MessageDetailsAdapter;
import com.mproject.customclass.Message;
import com.mproject.customclass.Project;
import com.mproject.customclass.Student;
import com.mproject.network.NetworkManager;
import com.mproject.network.ProgressBarManager;

public class Project_Message_Detail extends Activity implements OnClickListener{

	private ImageButton back_button;
	private TextView username;
	private ListView message_listview;
	private EditText message_box;
	private Button send_button;

	Project project;
	Student student;

	public static SharedPreferences mypref;

	public static boolean isCurrent = false;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.message_detail); 

		mypref=getSharedPreferences("My_Prefs",Activity.MODE_WORLD_WRITEABLE);

		Bundle extras=getIntent().getExtras();
		project=(Project) extras.getSerializable("project");
		student=(Student) extras.getSerializable("student");

		back_button = (ImageButton)findViewById(R.id.message_detail_back_button);
		username = (TextView)findViewById(R.id.message_detail_username);
		message_box = (EditText)findViewById(R.id.message_detail_chat_text);
		send_button = (Button)findViewById(R.id.message_detail_send);
		message_listview = (ListView)findViewById(R.id.message_detail_listview);

		username.setText(student.getName());

		back_button.setOnClickListener(this);
		send_button.setOnClickListener(this);

	}

	private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			fillTheList();      
		}
	}; 

	public void onResume() {
		super.onResume();
		isCurrent = true;
		fillTheList();
		registerReceiver(broadcastReceiver, new IntentFilter(C2DMMessageReceiver.BROADCAST_ACTION));
	}

	public void onPause() {
		super.onPause();
		isCurrent = false;
		unregisterReceiver(broadcastReceiver);
	}

	public void fillTheList() {

		try
		{
			ArrayList<Message> messageList = new ArrayList<Message>();
			messageList = NetworkManager.getMessageDetails(mypref.getString("user_id", ""), student.getUserID(), project.getID());
			/*messageList.add(new Message(true, "Day la tin nhan current user send"));
			messageList.add(new Message(false, "Day la tin nhan current user nhan haha"));*/
			MessageDetailsAdapter adapter = new MessageDetailsAdapter(this, R.layout.msg_details_row, messageList);
			ListView lv = (ListView) this.findViewById(R.id.message_detail_listview);

			lv.setStackFromBottom(true);
			// Set the ListView adapter
			lv.setAdapter(adapter);
		}catch(Exception e)
		{
			displayAlert();
			e.printStackTrace();
		}

	}

	public void displayAlert()
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this.getParent());
		builder.setMessage("No internet connection")
		.setNegativeButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
			}

		});
		AlertDialog alert = builder.create();
		alert.show();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == back_button) {
			finish();
		}
		if (v == send_button) {
			final String chatContent = message_box.getText().toString();

			Log.v("Message_Details",chatContent);
			//chatContent = chatContent.replace(" ","%20");


			ProgressBarManager manager=new ProgressBarManager(this.getParent())
			{
				String resp="empty";
				protected void onPreExecute() {

					Log.v("manager"," in pre execute");

					dialog.setMessage("Sending please wait...");
					dialog.setIndeterminate(true);

					// dialog.setTitle("Manager");
					dialog.show();
				}

				protected Boolean doInBackground(String... params) 
				{

					if (chatContent.length() > 0) {
						resp=NetworkManager.sendMessage(mypref.getString("user_id", ""), student.getUserID(), chatContent,project.getID());

					}
					return false;
				}
				protected void onPostExecute(Boolean result) {
					Log.v("manager"," in post execute");
					this.getDialog().dismiss();

					if(resp.equals("Error::User not yet registered"))
					{
						AlertDialog.Builder builder = new AlertDialog.Builder(Project_Message_Detail.this.getParent());
						builder.setMessage("Cannot Send, User Not Yet Registered")
						.setNegativeButton("OK", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}

						});
						AlertDialog alert = builder.create();
						alert.show();

					}
					else if(resp.equals("empty"))
					{
						AlertDialog.Builder builder = new AlertDialog.Builder(Project_Message_Detail.this.getParent());
						builder.setMessage("Cannot Send Empty Message")
						.setNegativeButton("OK", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}

						});
						AlertDialog alert = builder.create();
						alert.show();
					}
					else if(!resp.equals("success"))
					{
						displayAlert();
					}

					Log.e("Message_Details",resp);
					message_box.setText("");
					fillTheList();

				}

			};
			manager.execute();

		}

	}
}